#coding:utf-8
'''
Created on 2012-7-16

@author: wb_suoyao.shen
'''
import datetime
import os
import uuid
from PIL import Image
import logging
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render_to_response
from django.http import HttpResponse
from ssyblog import settings
from ssyblog.photos.models import Album
from ssyblog.photos.models import Photos
from ssyblog.photos.forms import PhotosForm
from ssyblog.common.constant import album_prefix_text

logger = logging.getLogger('main')

def photosAlbum(request):
    album_list = Album.objects.queryAlbumPreview()
    nav_parent = 'Album Manage'
    nav_child = 'Photos Add'
    current_nav = 'photos_manage'
    return render_to_response('cms/photos/photos_album.html',locals())

def addPhotos(request,albumId):
    folder = albumId
    photo_list = Photos.objects.all().filter(album = folder)
    nav_parent = 'Album Manage'
    nav_child = 'Photos Add'
    current_nav = 'photos_manage'
    return render_to_response('cms/photos/photos_add.html',locals())

@csrf_exempt
def uploadImg(request,folder):
    if request.method == 'POST':
        upload = request.FILES['Filedata']
        try:
            logger.info('begin to upload images...')
            file_ext = str(upload.name).split('.')[-1].lower()
            photo_folder = album_prefix_text + str(folder) + '/'
            upload_folder = settings.MEDIA_ROOT + photo_folder
            logger.info('upload folder is:[%s]...' % upload_folder)
            file_name = str(uuid.uuid1()) + '.' + file_ext
            # image path
            iamge_path = upload_folder + file_name
            # thumbnail iamge path
            thumbnail_path = upload_folder + album_prefix_text + file_name
            logger.info('image path is:[%s]...' % iamge_path)
            logger.info('thumbnail image path is:[%s]...' % thumbnail_path)
            # if not has photo folder, create it
            if not os.path.exists(upload_folder):
                os.mkdir(upload_folder)
            dest = open(iamge_path,'wb+')
            for block in upload.chunks():
                dest.write(block)
            dest.close()
            logger.info('upload images done...')
            #save thumbnail image
            logger.info('begin to create thumbnail images...')
            thumbnailImg(iamge_path,188,None,thumbnail_path,file_ext)
            logger.info('create thumbnail images done...')
            #save photo form
            logger.info('begin to save photosForm ...')
            image_column = photo_folder + file_name
            thumbnail_column = photo_folder + album_prefix_text + file_name
            form_column = {'album':folder, 'image':image_column, 'thumbnail':thumbnail_column, 'create_time':datetime.datetime.now()}
            form = PhotosForm(form_column)
            if form.is_valid():
                obj = form.save(commit=False)
                obj.save()
                logger.info('save photosForm done...')
        except IOError:
            logger.info('upload images failed:[%s]' % IOError.message)
    response = HttpResponse()
    response.write(thumbnail_column)
    return response

'''
create thumbnail image and save
'''
def thumbnailImg(filepath,width,height,thumbnail_path,ext):
    ext_list = ('gif','jpeg','png',)
    s_ext = ext.lower()
    if not ext in ext_list:
        s_ext = 'jpeg'
    image = Image.open(filepath)
    w,h = image.size
    if w < width:
        width = w
    if not height:
        height = h
    image.thumbnail((width,height),Image.ANTIALIAS)
    image.save(thumbnail_path,s_ext)
    
